#ifndef __ProcessPool_HPP__
#define __ProcessPool_HPP__

#include <iostream>
#include <vector>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "Task.hpp"
const int gdefaultnum = 5;

// 先描述
class Channel//对管道和子进程的封装类
{
public:
    Channel(int fd,pid_t id):_wfd(fd),_subid(id)
    {
        _name = "Channel-" + std::to_string(_wfd) + std::to_string(_subid); 
    }
    ~Channel(){}
    void Send(int code)
    {
        write(_wfd,&code,sizeof code);
    }
    void Close(){close(_wfd);}
    void Wait(){waitpid(_subid,nullptr,0);}
    std::string Name() const { return _name;}
    int Fd() const { return _wfd; }
    pid_t SubId() {return _subid;}
private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};
// 在组织
class ChannelMaager
{
public:
    ChannelMaager():_next(0){};
    Channel &select()
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }
    void Insert(int wfd,pid_t subid)
    {
        _channels.emplace_back(wfd,subid);
    }
    void Printchannel()
    {
        for(auto& channel : _channels)
        {
            std::cout << channel.Name() << std::endl;
        }
    }
    void StopSubprocess()
    {
        for(auto& channel : _channels)
        {
            channel.Close();
            std::cout << "关闭：" << channel.Name() << std::endl;
        }
    }
    void waitSubprocess()
    {
        for(auto& channel : _channels)
        {
            channel.Wait();
            std::cout << "回收：" << channel.Name() << std::endl;
        }
    }
    ~ChannelMaager(){}
private:
    std::vector<Channel> _channels;
    int _next;
};


class ProcessPool
{   
public:
    ProcessPool(int num) : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(Download);
        _tm.Register(Upload);
    }
    void work(int rfd)
    {
        while(true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                {
                    continue;
                }
                std::cout << "子进程[" << getpid() << "]收到一个任务码: " << code << std::endl;
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "读取错误" << std::endl;
                break;
            }
        }
    }
    void Debug()
    {
        _cm.Printchannel();
    }
    bool start()
    {
        for(int i = 0; i < _process_num; i++)
        {
            int pipefd[2] = {0};
            int n = pipe(pipefd);//传入 pipefd 数组，pipe() 会将管道的读端文件描述符存入 pipefd[0]，写端存入 pipefd[1]
            if(n < 0) return false;
            pid_t subid = fork();
            if(subid < 0) return false;
            else if(subid == 0)//子进程
            {
                close(pipefd[1]);
                work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else//父进程
            {
                close(pipefd[0]);
                _cm.Insert(pipefd[1],subid);//存的是父进程的管道写端
            }
        }
        return true;
    }
    void run()
    {
        auto &c = _cm.select();
        std::cout << "选择子进程：" << c.Name() << std::endl;
        int task_code = _tm.code();
        c.Send(task_code);
        std::cout << "发送任务代码：" << task_code << std::endl;
    }
    void Stop()
    {
        _cm.StopSubprocess();
        //回收子进程
        _cm.waitSubprocess();
    }
private:
    int _process_num;
    ChannelMaager _cm;
    TaskManager _tm;
};

#endif